<template>
	<view>
		<!-- <u-search v-model="keyword" :show-action="false" @change="searchlist" placeholder="请输入关键字"></u-search> -->
		<u-notify ref="uNotify"></u-notify>
		<u-list @scrolltolower="scrolltolower" v-if="carList != false || status == 'loading'">
			<u-list-item v-for="(item, index) in carList" :key="index">
				<u-cell :title="(index+1)+'、'+ item.Car.Name" @click="openpage" :name="item.Id">
					<view slot="label" style="font-size: 12px;color: #909193;line-height: 18px;">
						<span>{{'车牌号:' + (item.Car.CarNo || '') + ' 型号:' + (item.Car.Model || '') + ' 状态:'}}</span>
						<span
							:style="{'color': (item.Status == '已通过' ? 'green' : 'red' )}">{{(item.Status || '')}}</span>
					</view>
					<u-avatar slot="icon" shape="square" size="65"
						:src="item.Car.ImageList[0] ? `https://project.gxrunxiang.com/SysFile/download?id=${item.Car.ImageList[0].Id}` : ``"
						customStyle="margin: -3px 5px -3px 0"></u-avatar>
					<view slot="right-icon">
						<view style="display: flex;flex-direction: row; justify-content: center;align-items: center">
							<u-button type="primary" v-if="item.Status == '已通过'"
								@click.native.stop="toApply(item)">出车</u-button>
							<view v-if="item.Creator.Id == user.Id && item.Status != '使用中'" style="margin-left: 3px; color: red; font-size: 14px;"
								@click.native.stop="toDel(item.Id)">撤回</view>
						</view>			
					</view>
				</u-cell>
			</u-list-item>
			<u-modal :title="'车辆为:' + carName" :show="modalShow" @confirm="carOut(item)" :closeOnClickOverlay="true"
				@close="modalShow = false" style="z-index: 998;">
				<u--form labelWidth="auto" labelPosition="top" ref="uForm" :rules="rules" :model="applyForm">
					<u-form-item label="出发时里程表里程(KM)" :required="true" name="StartMileage" prop="StartMileage"><u--input
							v-model="applyForm.StartMileage" placeholder="请输入出发时里程表里程"
							type="number"></u--input></u-form-item>
					<u-form-item label="油表与里程表照"><u-upload :fileList="fileList1" @afterRead="afterRead"
							@delete="deletePic" name="1" multiple itype='油表与里程表照(出发)' :sizeType='["compressed"]'
							:maxCount="10"></u-upload></u-form-item>
					<!-- <u-form-item>
						<jp-signature-popup v-model="image" :openSmooth="true" />
					</u-form-item> -->
				</u--form>
			</u-modal>
			<u-modal :show="delmodalShow" title="提示" content='确认撤回申请?' @confirm="del" :showCancelButton="true"
				confirmText="是" cancelText="否" @cancel="delmodalShow = false" :closeOnClickOverlay="true"
				@close="delmodalShow = false"></u-modal>
			<u-loadmore :status="status" v-if="loading" />
		</u-list>
		<u-empty mode="data" icon="https://project.gxrunxiang.com/cdn/list.png" v-else>
		</u-empty>
	</view>
</template>

<script>
	import {
		baseUrl
	} from '@/common/config.js'
	import {
		getcarlist,
		addcarapply,
		getcarapply,
		carout,
		delapply,
		applyupdate,
		caroutstart
	} from '@/common/api.js'
	export default {
		data() {
			return {
				carList: [],
				keyWord: "",
				token: "",
				pageIndex: 1, //当前页数
				pageSize: 20, //页数大小
				totalPage: "", //总页数
				total: 0, //数据总数
				status: 'loadmore', //加载状态
				loading: true,
				modalShow: false,
				delmodalShow: false,
				delId: "",
				user: {},
				fileList1: [],
				itypelist: {
					"1": "油表与里程表照(出发)",
				},
				userfilter: {},
				carName: "",
				carId: "",
				applyForm: {
					StartMileage: ''
				},
				notifyData: {
					message: '出车成功',
					type: 'success',
					color: '#ffffff',
					bgColor: '',
					fontSize: 15,
					duration: 3000,
					safeAreaInsetTop: false
				},
				ErrorData: {
					message: '请提交油表与里程表照!',
					type: 'error',
					color: '#ffffff',
					bgColor: '',
					fontSize: 15,
					duration: 2000,
					safeAreaInsetTop: false
				},
				applyInfo: {},
				image: "",
				rules: {
					'StartMileage': {
						required: true,
						message: '请输入归还时里程表里程',
						trigger: ['blur']
					},
				},
			}
		},
		onLoad() {
			this.user = JSON.parse(uni.getStorageSync("$userinfo"))
			this.token = uni.getStorageSync("$token")
		},
		onShow() {
			this.carList = []
			this.getlist()
		},
		onReady() {
				// #ifdef MP-WEIXIN || MP-QQ || MP-BAIDU 
				//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
		    	this.$refs.uForm.setRules(this.rules)
				// #endif
		},
		methods: {
			dateFormat(date, fmt = "yyyy年MM月dd日") {
				if (date == null) return null;
				if (typeof date === "string") {
					date = date.slice(0, 19).replace("T", " ").replace(/-/g, "/");
					date = new Date(date);
				} else if (typeof date === "number") {
					date = new Date(date);
				}
				var o = {
					"M+": date.getMonth() + 1,
					"[Dd]+": date.getDate(),
					"h+": date.getHours(),
					"m+": date.getMinutes(),
					"s+": date.getSeconds(),
					"q+": Math.floor((date.getMonth() + 3) / 3),
					S: date.getMilliseconds(),
				};
				if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1
					.length));
				for (var k in o) {
					if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[
						k] : ("00" + o[k]).substr(("" + o[k]).length));
				}
				return fmt;
			},
			openpage(e) {
				uni.navigateTo({
					url: "applydetail?Id=" + e.name
				})
			},
			async getlist() {
				this.status = 'loading'
				// let querytype = this.$route.query.querytype
				let para = {
					Parameters: [{
						FieldName: "Status",
						ConditionalType: "IsNot",
						FieldValue: '已归还',
					}, ],
					OrderBys : ['PlanUseTime asc']
				}
				// if (this.keyword != "") {
				// 	this.userfilter = {
				// 		"ConditionalList": [{
				// 			"Key": 0,
				// 			"Value": {
				// 				"FieldName": "Name",
				// 				"FieldValue": this.keyword,
				// 				"ConditionalType": "Like"
				// 			}
				// 		}, {
				// 			"Key": 1,
				// 			"Value": {
				// 				"FieldName": "CarNo",
				// 				"FieldValue": this.keyword,
				// 				"ConditionalType": "Like"
				// 			}
				// 		}]
				// 	}
				// 	para.jsonPara = JSON.stringify([this.userfilter])
				// }
				para.OrderBys = ['CreateTime desc']
				para.pageSize = this.pageSize
				para.pageIndex = this.pageIndex
				await getcarapply(true, para).then(res => {
					let data = res.data
					this.carList.push(...data)
					this.total = res.count
					this.totalPage = Math.ceil(this.total / this.pageSize)
				})
				if (this.carList.length < this.pageSize) {
					this.loading = false; //如果数据列表小于当前页数，就让加载标签消失
					this.status = 'nomore';
				} else {
					this.status = 'loadmore';
				}

			},
			scrolltolower() {
				// 如果当前页数大于等于总页数，状态修改为没有更多了，不再继续往下执行代码
				if (this.pageIndex >= this.totalPage) {
					this.status = 'nomore';
					return;
				};
				this.status = 'loading'; //状态改为加载中
				this.pageIndex = ++this.pageIndex; //页面新增一页
				this.getlist(); //修改页数后，重新获取数据
			},
			// async searchlist() {
			// 	this.carList = [] //初始化
			// 	this.pageIndex = 1 //初始化当前页数为1
			// 	this.loading = true
			// 	await this.getlist()
			// },
			toApply(item) {
				this.carName = item.Car.Name
				this.carId = item.Id
				this.applyInfo = item
				this.modalShow = true
			},
			toDel(Id) {
				this.delId = Id
				this.delmodalShow = true
			},
			del() {
				let ids = []
				ids.push(this.delId)
				delapply(ids).then((res) => {
					if (res == true)
						uni.navigateBack()
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				console.log(event.name);
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, this.itypelist[event.name])
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, itype) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${baseUrl}/SysFile/upload?outid=${this.applyInfo.Id}&type=${itype}`,
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						header: {
							"Authorization": `Bearer ${this.token}`
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
			uploadimagePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${baseUrl}/SysFile/upload?outid=${this.applyInfo.Id}&type=签名`,
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						header: {
							"Authorization": `Bearer ${this.token}`
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
			carOut() {
				// this.uploadimagePromise(this.image)
				if (this.fileList1.length == 0) {
					this.$refs.uNotify.show(this.ErrorData)
				} else {
					this.$refs.uForm.validate().then(res => {
						this.applyInfo.StartMileage = this.applyForm.StartMileage
						// applyupdate(this.applyInfo).then(res=>{
						// 	console.log(res);
						// })
						carout(this.applyInfo).then(res => {
							if (res == true) {
								this.$refs.uNotify.show(this.notifyData)
								setTimeout(() => {
									uni.navigateBack()
								}, 1000)
							}
						})
					}).catch(errors => {
						uni.$u.toast('请填写必填参数！')
					})
				}
			},
		},
	}
</script>

<style>

</style>